package org.hshk.message.controller;

import com.google.gson.Gson;
import io.swagger.annotations.Api;
import org.hshk.message.BaseController;
import org.hshk.message.entity.CpMsgTemplate;
import org.hshk.message.service.CpMsgTemplateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created With IntelliJ IDEA
 * User: gc
 * Date: 2017/2/27 0027
 * Time: 10:03
 * ProjectName: msgCenterAPI
 * To change this template use File
 */
@Api(value = "短信模板 API")
@RestController
@RequestMapping("/templates")
public class MsgTemplateAddController extends BaseController
{
    //日志记录类
    private static final Logger log = LoggerFactory.getLogger(MsgTemplateAddController.class);
    @Autowired
    private CpMsgTemplateService cpMsgTemplateService;
    
    //线程对象暂存
    private ThreadLocal<Gson> local = new ThreadLocal<Gson>();
    //对象存放类
    private Gson getGson()
    {
        if(null == local.get())
        {
            Gson gson = new Gson();
            local.set(gson);
        }
        return local.get();
    }
    
    /**
     * 2017年2月27日 10:04:31
     * 添加当前品牌下所需要的模版名称
     * 注意：一般是在新增商户时需要运行的方法
     * tpBrandId值为：以某一个商户的模版为例，复制一套
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addTemplateByBrandId(@RequestParam("tpBrandId") int tpBrandId, 
                                       @RequestParam("brandId") int brandId)
    {
        try
        {
            log.info("MsgTemplateAddController.addTemplateByBrandId [ brandId=" + brandId 
                    + ", tpBrandId=" + tpBrandId + " ]");
            //先获取源品牌下的模版
            List<CpMsgTemplate> tpCpMsgTemplateList = cpMsgTemplateService.findByBrandId(tpBrandId);
            //当前品牌下面有模版
            if(null != tpCpMsgTemplateList)
            {
                List<CpMsgTemplate> cpMsgTemplateList = cpMsgTemplateService.findByBrandId(brandId);
                if(null == cpMsgTemplateList)
                {
                    cpMsgTemplateService.saveTemplate(tpCpMsgTemplateList, brandId);
                    return getGson().toJson("[ brandId=" + brandId + " 新增模版成功.]");
                }else
                {
                    return getGson().toJson(fail("[ brandId=" + brandId + " 下已经存在模版, 不需新增. ]"));
                }
            }else
            {
                return getGson().toJson(fail("[ tpBrandId=" + tpBrandId + " 下没有模版信息, 请更换有模版信息的品牌.]"));
            }
        }catch(Exception ex)
        {
            ex.printStackTrace();
            log.error(ex.getMessage() + " MsgTemplateAddController.addTemplateByBrandId [ brandId=" + brandId 
                    + ", tpBrandId=" + tpBrandId + " ]");
            return getGson().toJson(fail("失败"));
        }
    }

    
}